package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author Dui
 * @since 2022/11/1 16:39
 */
@Slf4j
//annotations指定拦截范围
//@RestControllerAdvice = @ControllerAdvice + @ResponseBody
@RestControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        String message = exception.getMessage();
        //重复数据的问题
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            //重复的数据
            String duplicateKey = split[2];
            return R.error(duplicateKey + "===数据已存在！");
        }
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception){
        String message = exception.getMessage();
        return R.error(message);
    }
}